/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package convenios;

import com.thoughtworks.xstream.XStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;


public class Database {

     private ArrayList<User> usuarios = new ArrayList<User>();

    public Database (){

     XStream stream = new XStream();

         FileInputStream inputStream = null;
         try {
             inputStream = new FileInputStream("users.xml");
             usuarios = (ArrayList<User>) stream.fromXML(inputStream);
               } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Erro! Problema encontrado ao carregar a lista de usuários!");
             }

    }

    public void addUser(User user) {

        usuarios.add(user);
        updateUser();

    }

    public User  getUserbySiape(String siape) {

        int i;
        User mat = null;

        for (i = 0; i < getUsuarios().size(); i++) {
            if (getUsuarios().get(i).getSiape().equals(siape)) {
                mat = getUsuarios().get(i);
                return mat;
            }
        }
        return null;

    }

    public Convenio getConveniobyID(int id) {
          XStream stream = new XStream();

         FileInputStream inputStream = null;
         try {
             inputStream = new FileInputStream(id + ".xml");
             Convenio conv = (Convenio) stream.fromXML(inputStream);
             return conv;
         } catch (FileNotFoundException ex) {
                JOptionPane.showMessageDialog(null, "Erro! Convenio não encontrado!");
                return null;
         }
    }

  public  void newConv(Convenio conv) {

        //fazer verificacoes se ja n existe o numero e tals

          XStream xstream = new XStream();
           String xml = xstream.toXML(conv);

           BufferedWriter out;
        try {
            out = new BufferedWriter(new FileWriter(conv.getId() + ".xml"));
            out.write(xml);
            out.flush();
            out.close();
           JOptionPane.showMessageDialog(null, "Convênio adicionado com sucesso!");

           User usuario = getUserbySiape(conv.getSiape());
           usuario.addConv(conv.getId());

           updateUser();
           

        } catch (IOException ex) {
         JOptionPane.showMessageDialog(null, "Erro! Problema encontrado ao gravar o Convênio!");
        }
    }

    public String[] getListUsers() {
        String[] lista = new String[getUsuarios().size()];
                 
          for (int i = 0; i < getUsuarios().size(); i++) {
            lista[i] = getUsuarios().get(i).getNome();
      }
      return lista;
    }

    String getSiapeByName(String nome) {

          int i;
        User mat = null;

        for (i = 0; i < getUsuarios().size(); i++) {
            if ( getUsuarios().get(i).getNome().equalsIgnoreCase(nome)) {
                    return getUsuarios().get(i).getSiape();
            }
        }
        return null;
        
    }


    public ArrayList<User> getUsuarios() {
        return usuarios;
    }

     
    public String[] getConvbyUser(User localuser) {

        ArrayList<Integer> lista = localuser.getConvenios();

      
        if(lista.isEmpty()){
            String texto[] = new String[1];
            texto[0]="Nenhum Convênio cadastrado.";
            return texto;
        }

          String texto[] = new String[lista.size()];
         for (int i = 0; i < localuser.getConvenios().size(); i++) {
            Convenio conv = getConveniobyID(lista.get(i));
            texto[i] = conv.getId() + " " + conv.getAssunto();

        }
        return texto;
    }

    private void updateUser() {


       XStream xstream = new XStream();

           String xml = xstream.toXML(usuarios);

        BufferedWriter out;
        try {
            out = new BufferedWriter(new FileWriter("users.xml"));
            out.write(xml);
            out.flush();
            out.close();

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Erro! Problema encontrado ao gravar os dados do usuário!");
        }


    }

    void updateConv(Convenio conv) {
         XStream xstream = new XStream();
           String xml = xstream.toXML(conv);

           BufferedWriter out;
        try {
            out = new BufferedWriter(new FileWriter(conv.getId() + ".xml"));
            out.write(xml);
            out.flush();
            out.close();
           JOptionPane.showMessageDialog(null, "Convênio alterado com sucesso!");
                  
        } catch (IOException ex) {
         JOptionPane.showMessageDialog(null, "Erro! Problema encontrado ao gravar o Convênio!");
        }
    }




    
}


